package cn.edu.scau.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.scau.Bean.ClassPage;
import cn.edu.scau.Bean.Classes;
import cn.edu.scau.Jdbc.JdbcUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ClassServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=utf-8");

		String type = req.getParameter("type");

		if (type != null) {

			printJason(req, resp, type);
		} else {

			sendRed(req, resp);
		}


	}
	
	
	private void sendRed(HttpServletRequest req, HttpServletResponse resp) throws IOException{

		ClassPage classPage = new ClassPage();
		List<Classes> classes = JdbcUtils.getClasses(classPage);
		req.getSession().setAttribute("classPage", classPage);
		req.getSession().setAttribute("classes", classes);

		resp.sendRedirect("/Tables/data/classes.jsp");
	}
	
	
	private void printJason(HttpServletRequest req, HttpServletResponse resp, String type) throws IOException {

		ClassPage classPage = (ClassPage) req.getSession().getAttribute("classPage");

		switch (type) {

		case "first":
			classPage.setCurrentPage(1);
			break;
		case "pre":
			if (classPage.getCurrentPage() != 1) {
				classPage.setCurrentPage(classPage.getCurrentPage() - 1);
			}
			break;
		case "next":
			if (classPage.getCurrentPage() != classPage.getMaxPage()) {
				classPage.setCurrentPage(classPage.getCurrentPage() + 1);
			}
			break;
		case "last":
			classPage.setCurrentPage(classPage.getMaxPage());
			break;

		}

		List<Classes> classes = JdbcUtils.getClasses(classPage);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("classes", classes);
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(jsonObject);

		req.getSession().setAttribute("classes", classes);

		PrintWriter pw = resp.getWriter();
		pw.write(jsonArray.toString());
	}

}
